import 'package:flutter/foundation.dart';

/// 上传任务状态枚举
enum UploadTaskStatus {
  pending, // 等待上传
  uploading, // 上传中
  paused, // 已暂停
  completed, // 已完成
  failed, // 失败
  cancelled, // 已取消
}

/// 上传任务类型枚举
enum UploadTaskType {
  smallFile, // 小文件上传
  chunkFile, // 分片上传
}

/// 上传任务模型
class UploadTask {
  final String id;
  final String filePath;
  final String fileName;
  final int fileSize;
  final int directoryId;
  final UploadTaskType type;
  UploadTaskStatus status;
  double progress;
  String? errorMessage;
  DateTime createTime;
  DateTime? updateTime;

  UploadTask({
    required this.id,
    required this.filePath,
    required this.fileName,
    required this.fileSize,
    required this.directoryId,
    required this.type,
    this.status = UploadTaskStatus.pending,
    this.progress = 0.0,
    this.errorMessage,
    required this.createTime,
    this.updateTime,
  });

  /// 更新任务状态
  void updateStatus(UploadTaskStatus newStatus, {String? error}) {
    status = newStatus;
    errorMessage = error;
    updateTime = DateTime.now();
  }

  /// 更新上传进度
  void updateProgress(double newProgress) {
    progress = newProgress;
    updateTime = DateTime.now();
  }

  /// 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'filePath': filePath,
      'fileName': fileName,
      'fileSize': fileSize,
      'directoryId': directoryId,
      'type': type.toString(),
      'status': status.toString(),
      'progress': progress,
      'errorMessage': errorMessage,
      'createTime': createTime.toIso8601String(),
      'updateTime': updateTime?.toIso8601String(),
    };
  }

  /// 从Map创建实例
  factory UploadTask.fromMap(Map<String, dynamic> map) {
    return UploadTask(
      id: map['id'],
      filePath: map['filePath'],
      fileName: map['fileName'],
      fileSize: map['fileSize'],
      directoryId: map['directoryId'],
      type: UploadTaskType.values.firstWhere(
        (e) => e.toString() == map['type'],
        orElse: () => UploadTaskType.smallFile,
      ),
      status: UploadTaskStatus.values.firstWhere(
        (e) => e.toString() == map['status'],
        orElse: () => UploadTaskStatus.pending,
      ),
      progress: map['progress'],
      errorMessage: map['errorMessage'],
      createTime: DateTime.parse(map['createTime']),
      updateTime:
          map['updateTime'] != null ? DateTime.parse(map['updateTime']) : null,
    );
  }
}
